/**
 * Created by apple on 2018/1/9.
 */
var express = require('express');
var router = express.Router();

var request = require('request');
var AlipayInfoRouter = module.exports;
var Alipay = require('../libs/alipay_usuz/alipay.js');
var AlipayConfig = require('../db/alipay_config.json').alipay_usuz_cfg;
var AlipayInfoDao = require('../dao/alipayInfo');
var moment = require('moment');
var UserToken = require('../db/user_tokens.js');

const app_id = '2018010401570073'; //支付宝分配给开发者的应用ID
const ali_pid = '2088921556854580';     //签约的支付宝账号对应的支付宝唯一用户号，以2088开头的16位纯数字组成

//参数
AlipayInfoRouter.save = function (req,res) {
    var par = paramAll(req);
    if (!par.user_id) return res.json(new ERR('user_id不为空', 400));
    if (!par.auth_code) return res.json(new ERR('auth_code不为空', 400));
    if (!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    UserToken.checkUserLogin(par.token,function (err,errCode,userInfo) {
        if (err) return res.json(new ERR(err, errCode));
        par.uid = userInfo.uid;
        par.account = userInfo.account; //用户后续增加有效人数
        AlipayInfoDao.saveAlipayUserId(par,function (err,data) {
            if(err) return res.json(new ERR(err, 400));
            res.json(new PKG({res:'授权成功!'}));
        });
        //另外去获取阿里用户信息
        getAndSaveAlipayInfo(par.auth_code);
    });
};
router.post('/save', AlipayInfoRouter.save);

//根据auth_code获取用户信息
function getAndSaveAlipayInfo(auth_code){
    getAlipayInfo(auth_code,function (err,alipayInfo) {
        if (err) {
            console.log(err);
            return;
        }
        AlipayInfoDao.saveAlipayInfo(alipayInfo,function (err) {
            if (err) {
                console.log(err);
                return;
            }
            console.log('保存阿里信息成功')
        })
    });
}

function getAlipayInfo(auth_code,cb) {
    getAlipayToken(auth_code,function (err,token) {
        if (err) return cb(err);
        getAlipayInfoWithToken(token,cb);
    });
}

function getAlipayToken(auth_code,cb) {

    var method = "alipay.system.oauth.token";
    var charset = 'utf-8';
    var sign_type = "RSA";
    var timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
    var version = "1.0";
    var grant_type = 'authorization_code';

    var sParaTemp = [];
    sParaTemp.push(["app_id", app_id]);
    sParaTemp.push(["method", method]);
    sParaTemp.push(["charset", charset]);
    sParaTemp.push(["sign_type", sign_type]);
    sParaTemp.push(["timestamp", timestamp]);
    sParaTemp.push(["version", version]);
    sParaTemp.push(["grant_type", grant_type]);
    sParaTemp.push(["code", auth_code]);
    var sPara = Alipay.buildRequestPara2(sParaTemp);
    var sURL = Alipay.getPath('', sPara);
    request({
        url: 'https://openapi.alipay.com/gateway.do?' + sURL,
        method: 'GET',
        headers: {
            'charset': 'utf-8'
        }
    },function(error, response, body){

        if (error) {
            console.log(error);
            return cb(error);
        }
        try {
            body = JSON.parse(body);
        } catch (e) {
            cb(e);
            return;
        }
        var response = body.alipay_system_oauth_token_response;
        if (!response || !response.access_token) return cb('返回有误');
        cb(null,response.access_token);
    });
}


function getAlipayInfoWithToken(token,cb) {

// var total_fee = 0.01;
    var method = "alipay.user.info.share";
    var charset = 'utf-8';
    var sign_type = "RSA";
    var timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
    var version = "1.0";

    var sParaTemp = [];
    sParaTemp.push(["app_id", app_id]);
    sParaTemp.push(["method", method]);
    sParaTemp.push(["charset", charset]);
    sParaTemp.push(["sign_type", sign_type]);
    sParaTemp.push(["timestamp", timestamp]);
    sParaTemp.push(["version", version]);
    sParaTemp.push(["auth_token", token]);
    var sPara = Alipay.buildRequestPara2(sParaTemp);
    var sURL = Alipay.getPath('', sPara);
    request({
        url: 'https://openapi.alipay.com/gateway.do?' + sURL,
        method: 'GET',
        headers: {
            'charset': 'utf-8'
        }
    },function(error, response, body){
        console.log("支付宝返回内容:\n", body);

        if (error) {
            console.log(error);
            return cb(error);
        }
        try {
            body = JSON.parse(body);
        } catch (e) {
            cb(e);
            return;
        }
        var response = body.alipay_user_info_share_response;
        if (!response || response.msg != 'Success') return cb('返回有误');
        var alipayinfo = {
            user_id:response.user_id,
            avatar:response.avatar,
            city:response.city,
            gender:response.gender,
            is_certified:response.is_certified,
            is_student_certified:response.is_student_certified,
            nick_name:response.nick_name,
            province:response.province,
            user_status:response.user_status,
            user_type:response.user_type
        };
        cb(null,alipayinfo);

    });
}


AlipayInfoRouter.getLoginInfo = function (req,res) {
    var par = paramAll(req);

    UserToken.checkUserLogin(par.token,function (err,errCode,userInfo) {
        if (err) return res.json(new ERR(err, errCode));

        var sParaTemp = [];
        sParaTemp.push(["apiname", 'com.alipay.account.auth']);
        sParaTemp.push(["app_id", app_id]);
        sParaTemp.push(["app_name", 'mc']);
        sParaTemp.push(["auth_type", 'AUTHACCOUNT']);
        sParaTemp.push(["biz_type", 'openservice']);
        sParaTemp.push(["method", 'alipay.open.auth.sdk.code.get']);
        sParaTemp.push(["pid", ali_pid]);
        sParaTemp.push(["product_id", 'APP_FAST_LOGIN']);
        sParaTemp.push(["scope", 'kuaijie']);
        sParaTemp.push(["sign_type", 'RSA']);
        sParaTemp.push(["target_id", userInfo.uid]);

        var sPara = Alipay.buildRequestPara2(sParaTemp);

        var sURL = Alipay.getPath('', sPara);
        console.log(sURL);
        res.json(new PKG({info:sURL}));
    });
}
router.post('/getLoginInfo', AlipayInfoRouter.getLoginInfo);


/**
 * 获取支付宝用户唯一ID
 * @param  token
 * @param  app_sid
 *         url//alipay_info/getAliUserId
 */
AlipayInfoRouter.getAliUserId = function(req, res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('请重新登录', 400));
    if(!par.app_sid) return res.json(new ERR('app_sid不为空！', 400));
    UserToken.checkUserLogin(par.token,function (err,errCode,userInfo) {
        if (err) return res.json(new ERR(err, errCode));
        par.uid = userInfo.uid;
        AlipayInfoDao.getAliUserId(par, function(e, data) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/getAliUserId', AlipayInfoRouter.getAliUserId);

/*
 @param token
 @param app_sid
 //绑定淘宝
*/
AlipayInfoRouter.firstAuthorizeTB = function (req,res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('请重新登录', 400));
    if(!par.app_sid) return res.json(new ERR('app_sid不为空！', 400));
    UserToken.checkUserLogin(par.token,function (err,errCode,userInfo) {
        if (err) return res.json(new ERR(err, errCode));
        par.uid = userInfo.uid;
        AlipayInfoDao.firstAuthorizeTB(par, function(e, data) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/firstAuthorizeTB', AlipayInfoRouter.firstAuthorizeTB);


module.exports = router;